package supremeragcalc.util.gui;

import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;

public class ColorMask {
	
	/**
	 * This implement a color mask to make an image background transparent
	 * 
	 * @param img: Image to apply the mask
	 * @param keyColor: Color to make transparent
	 * @return an image with a mask applied
	 */
	public static Image applyMask(Image img, Color keyColor) {  
		int imgWidth = img.getWidth(null);
		int imgHeight = img.getHeight(null);
		int[] pxls = getPixels(img);
		for (int i = 0; i < pxls.length; i++) {
			if (pxls[i] == keyColor.getRGB()) {
				pxls[i] = 0x00ffffff;
			}
		}
		return getImage(pxls, imgWidth, imgHeight);
	}
	

	private static final Image getImage(int[] pixels, int w, int h) {  
		MemoryImageSource source = new MemoryImageSource(w, h, pixels, 0, w);  
		return Toolkit.getDefaultToolkit().createImage(source);
	}  

	
	private static int[] getPixels(Image img) {  
		int[] pix = new int[img.getWidth(null) * img.getHeight(null)];  
		PixelGrabber pg = new PixelGrabber (img, 0, 0, img.getWidth(null), img.getHeight(null), pix, 0, img.getWidth(null));  
		try {
			pg.grabPixels();
			
		} catch (InterruptedException e) {
			System.out.println("ColorMask: Another thread has interrupted this thread.");
			e.printStackTrace();
		}  
		return pix;  
	}
}
